#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "sql_adapter.h"
#include "linux_controller.h"
#include "file_controller.h"
#include "setting.h"
#include "SystemCall.h"
#include <QWidget>
#include <QTableView>
#include <QSqlTableModel>
#include <QSqlRecord>
#include <QMessageBox>
#include <QRegularExpression>
#include <QFile>
#include <QtConcurrent/QtConcurrent>
#include <QFileInfo>

using namespace QtConcurrent;

void show_msg_box(QString tip)
{
    QMessageBox msg("Gbase8c Pro Tip",
                   tip,
                   QMessageBox::NoIcon,
                   QMessageBox::NoButton,
                   QMessageBox::NoButton,
                   QMessageBox::NoButton);
    msg.exec();
}

QStringList* opened_table = new QStringList();
QMap<QString, QTableView*> table_model;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    setting = new software_set();

    ui -> setupUi(this);
    ui -> check_edit -> setVisible(false);
    ui -> check_lab -> setVisible(false);
    ui -> data_length -> setVisible(false);
    ui -> length_edit -> setVisible(false);
    ui -> menuBar -> setVisible(false);

    if(SystemController::GetSystemType() == Windows)
    {
        ui -> db_status_frame -> setEnabled(false);
    }
    else
    {
        QtConcurrent::run(get_db_status, ui -> db_status, ui -> db_botton, ui -> NodeList, ui -> NodeListDetail);
    }

    setting -> SetWindowStyle(this, setting -> StyleColor);
}

MainWindow::~MainWindow()
{
    disconnect_to_sql();
    delete ui;
}

void MainWindow::get_all_table()
{
    //获得数据库里面所有表
    ui -> table_list -> clear();
    ui -> table_list -> addItems(get_all_tables());
}

void MainWindow::on_start_connect_clicked()
{
    if(connect_to_sql(ui))
    {
        ui -> stackedWidget -> setCurrentIndex(1);

        get_all_table();

        ui -> menuBar -> setVisible(true);
    }
}

QHash<QAbstractItemModel*, QSqlTableModel*> view_model;

void MainWindow::backup_operating_table()
{
    QString name = ui -> table_index -> tabText(ui -> table_index -> currentIndex());

    if(name.isEmpty())
    {
        name = ui -> table_index -> tabText(ui -> table_index -> currentIndex());
    }

    QtConcurrent::run(backup_table, view_model[table_model[name] -> model()], name);
    //backup_table(view_model[table_model[name] -> model()], name);
}

void MainWindow::paint_new_table(QString currentText)
{
    QSqlTableModel* model = new QSqlTableModel(this, db);
    model -> setTable(currentText);
    model -> setEditStrategy(QSqlTableModel::OnManualSubmit);
    model -> select();

    QTableView* new_table = new QTableView();
    new_table -> setGeometry(150, 0, 1211, 611);
    new_table -> setModel(model);
    new_table -> setEditTriggers(QAbstractItemView::NoEditTriggers);
    new_table -> horizontalHeader() -> setSectionResizeMode(QHeaderView::Stretch);  //所有列都扩展自适应宽度，填充充满整个QTableView宽度
    new_table -> horizontalHeader() -> setMinimumSectionSize(100);

    table_model.insert(currentText, new_table);
    view_model.insert(new_table -> model(), model);

    ui -> table_index -> addTab(new_table, currentText);
}

void MainWindow::on_table_list_currentTextChanged(const QString &currentText)
{
    if(currentText != "")
    {

    }
}

void MainWindow::on_create_table_clicked()
{
    ui -> stackedWidget -> setCurrentIndex(2);
    ui -> menuBar -> setVisible(false);
}

void MainWindow::on_data_box_currentTextChanged(const QString &arg1)
{
    if(arg1.contains("CHAR") || arg1.contains("TEXT"))
    {
        ui -> data_length -> setVisible(true);
        ui -> length_edit -> setVisible(true);
    }
    else
    {
        ui -> data_length -> setVisible(false);
        ui -> length_edit -> setVisible(false);
    }
}

void MainWindow::on_constraint_box_currentTextChanged(const QString &arg1)
{
    if(arg1.contains("CHECK"))
    {
        ui -> check_lab -> setText("CHECK:");
        ui -> check_lab -> setVisible(true);
        ui -> check_edit -> setVisible(true);
        ui -> check_edit -> setText("CHECK()");
    }
    else if(arg1.contains("FOREIGN"))
    {
        ui -> check_lab -> setText("FOREIGN:");
        ui -> check_lab -> setVisible(true);
        ui -> check_edit -> setVisible(true);
        ui -> check_edit -> setText("references 被参照表(被参照列)");
    }
    else
    {
        ui -> check_lab -> setVisible(false);
        ui -> check_edit -> setVisible(false);
    }
}

bool containsSpecialChar(QString& str)
{
    static QRegularExpression regExp("[!@#$%^&;*() +\\-=\\[\\]{};':\"\\\\|,.<>\\/?]");
    QRegularExpressionMatch match = regExp.match(str);

    return match.hasMatch();
}

bool table_contain_arrange(QTableWidget* table, QString arrange_name)
{
    for(int i = 0; i < table -> rowCount(); i++)
    {
        if(table -> item(i, 0) -> text() == arrange_name)
        {
            return true;
        }
    }
    return false;
}

void MainWindow::on_add_arrange_clicked()
{
    QString arrange_name = ui -> name_edit -> text();
    if(containsSpecialChar(arrange_name))
    {
        QMessageBox mbox;
        mbox.setText("属性名存在非法字符");
        mbox.exec();
    }
    else if(arrange_name.length() <= 0)
    {
        QMessageBox mbox;
        mbox.setText("属性名不存在");
        mbox.exec();
    }
    else if((ui -> data_box -> currentText().contains("CHAR") || ui -> data_box -> currentText().contains("TEXT")) \
               && ui -> length_edit -> text().toDouble(new bool()) == false)
    {
        QMessageBox mbox;
        mbox.setText("类型长度不是数字");
        mbox.exec();
    }
    else if(table_contain_arrange(ui -> new_table_info, ui -> name_edit -> text()))
    {
        QMessageBox mbox;
        mbox.setText("列名重复");
        mbox.exec();
    }
    else if(ui -> name_edit -> text()[0] >= '0' && ui -> name_edit -> text()[0] <= '9')
    {
        QMessageBox mbox;
        mbox.setText("列名不能以数字开头");
        mbox.exec();
    }
    else
    {
        ui -> new_table_info -> setRowCount(ui -> new_table_info -> rowCount() + 1);

        ui -> new_table_info -> setItem(ui -> new_table_info -> rowCount() - 1, 0, new QTableWidgetItem(ui -> name_edit -> text()));

        QString data_kind = ui -> data_box -> currentText();
        if(ui -> data_box -> currentText().contains("CHAR") || ui -> data_box -> currentText().contains("TEXT"))
        {
            data_kind = data_kind + "(" + ui -> length_edit -> text() + ")";
        }
        ui -> new_table_info -> setItem(ui -> new_table_info -> rowCount() - 1, 1, new QTableWidgetItem(data_kind));

        QString constraint_str;
        if(ui -> constraint_box -> currentText().contains("CHECK") || ui -> constraint_box -> currentText().contains("FOREIGN"))
        {
            constraint_str = ui -> check_edit -> text();
        }
        else
        {
            constraint_str = ui -> constraint_box -> currentText();
        }
        ui -> new_table_info -> setItem(ui -> new_table_info -> rowCount() - 1, 2, new QTableWidgetItem(constraint_str));
    }
}

void MainWindow::on_delete_arrange_clicked()
{
    ui -> new_table_info -> removeRow(ui -> new_table_info -> currentRow());
}

void MainWindow::on_new_table_info_cellClicked(int row, int column)
{
    ui -> delete_arrange -> setEnabled(true);
}

void MainWindow::on_exit_create_page_clicked()
{
    ui -> stackedWidget -> setCurrentIndex(1);
    ui -> new_table_info -> clear();
    ui -> new_table_info -> setRowCount(0);
    ui -> menuBar -> setVisible(true);
}

bool MainWindow::primary_key_exist()
{
    for(int i = 0; i < ui -> new_table_info -> rowCount(); i++)
    {
        if(ui -> new_table_info -> item(i, 2)->text() == "PRIMARY KEY")
        {
            return true;
        }
    }
    return false;
}

void MainWindow::on_add_table_clicked()
{
    QString table_name = ui -> table_name_input -> text();
    if(containsSpecialChar(table_name))
    {
        QMessageBox mbox;
        mbox.setText("表名存在非法字符");
        mbox.exec();
    }
    else if(table_name.length() <= 0)
    {
        QMessageBox mbox;
        mbox.setText("表名不存在");
        mbox.exec();
    }
    else if(get_all_tables().contains(table_name))
    {
        QMessageBox mbox;
        mbox.setText("表名重复");
        mbox.exec();
    }
    else if(table_name[0] >= '0' && table_name[0] <= '9')
    {
        QMessageBox mbox;
        mbox.setText("表名不能以数字开头");
        mbox.exec();
    }
    else if(ui -> new_table_info -> rowCount() <= 0)
    {
        QMessageBox mbox;
        mbox.setText("列属性数量小于0");
        mbox.exec();
    }
    else if(primary_key_exist() == false)
    {
        QMessageBox mbox;
        mbox.setText("主键不存在");
        mbox.exec();
    }
    else
    {
        add_new_table(ui -> new_table_info, ui -> table_name_input -> text());
        ui -> table_list -> addItem(table_name);
    }
}

void MainWindow::on_table_index_tabBarClicked(int index)
{
    QString name = ui -> table_index -> tabText(index);
    for(int i = 0; i < ui -> table_list -> count(); i++)
    {
        if(ui -> table_list -> item(i) -> text() == name)
        {
            ui -> table_list -> setCurrentRow(i);
        }
    }
}

void MainWindow::on_delete_table_clicked()
{
    if(setting -> backup_table_before_change_table)
    {
        backup_operating_table();
    }

    ui -> export_2 -> setEnabled(false);

    QString table_name = ui -> table_list -> currentItem() -> text();

    opened_table -> removeOne(table_name);

    //delete from db
    delete_table(table_name);

    //delete from table index
    //ui -> table_index -> removeTab(ui -> table_index -> currentIndex());

    //fresh tables list
    QListWidgetItem* temp = ui -> table_list -> currentItem();
    ui -> table_list -> removeItemWidget(temp);
    delete temp;

    //ui -> table_list -> setCurrentRow(0);
    //ui -> table_list -> setCurrentItem(ui -> table_list -> item(0));

    //delete map and list
    view_model.remove(table_model[table_name] -> model());
    delete table_model[table_name];
    table_model.remove(table_name);

    //close button
    ui -> delete_table -> setEnabled(false);
    ui -> clear_table -> setEnabled(false);
    ui -> update_table -> setEnabled(false);
}

void MainWindow::on_clear_table_clicked()
{
    if(setting -> backup_table_before_change_table)
    {
        backup_operating_table();
    }

    clear_table(ui -> table_list -> currentItem() -> text());
}

void MainWindow::on_update_table_clicked()
{
    if(setting -> backup_table_before_change_table)
    {
        backup_operating_table();
    }

    ui -> stackedWidget -> setCurrentIndex(3);

    if(ui -> table_list -> currentItem() -> text().isEmpty())
    {
        ui -> writing_table -> setModel(table_model[ui -> table_index -> tabText(ui -> table_index -> currentIndex())] -> model());
    }
    else
    {
        ui -> writing_table -> setModel(table_model[ui -> table_list -> currentItem() -> text()] -> model());
    }
    ui -> menuBar -> setVisible(false);
}

void MainWindow::on_table_index_currentChanged(int index)
{
    QString name = ui -> table_index -> tabText(index);
    for(int i = 0; i < ui -> table_list -> count(); i++)
    {
        if(ui -> table_list -> item(i) -> text() == name)
        {
            ui -> table_list -> setCurrentRow(i);
        }
    }
}

void MainWindow::on_table_list_itemDoubleClicked(QListWidgetItem *item)
{
    QString currentText = item -> text();
    if(currentText != "")
    {
        //open button, but can change system table
        if(!is_system_tables(currentText))
        {
            ui -> delete_table -> setEnabled(true);
            ui -> clear_table -> setEnabled(true);
            ui -> fresh_table -> setEnabled(true);
        }
        //show table index
        if(opened_table -> contains(currentText))
        {
            ui -> table_index -> setCurrentIndex(opened_table -> indexOf(currentText));
        }
        else
        {
            paint_new_table(currentText);
            opened_table -> append(currentText);
            ui -> table_index -> setCurrentIndex(opened_table -> indexOf(currentText));
        }
        ui -> update_table -> setEnabled(true);
        ui -> export_2 -> setEnabled(true);
    }
}

void MainWindow::on_read_odbc_ini_clicked()
{
    odbc_ini* ini = new odbc_ini();

    if(ini -> file_status)
    {
        ui -> odbc_input -> setText(ini -> odbc_source);
        ui -> ip_input -> setText(ini -> ip);
        ui -> port_input -> setText(ini -> port);
        ui -> uid_input -> setText(ini -> uid);
        ui -> pwd_input -> setText(ini -> pwd);
    }

    delete ini;
}

bool table_changed = false;

void MainWindow::on_new_tunple_clicked()
{
    table_changed = true;
    ui -> writing_table -> model() -> insertRow(ui -> new_table_info -> model() -> rowCount());
}

void MainWindow::on_writing_table_clicked(const QModelIndex &index)
{
    ui -> delete_choose -> setEnabled(true);
}

void MainWindow::on_delete_choose_clicked()
{
    table_changed = true;
    ui -> writing_table -> model() -> removeRow(ui -> writing_table -> currentIndex().row());
}

void MainWindow::on_upgrade_change_clicked()
{
    if(table_changed)
    {
        if(!view_model[ui -> writing_table -> model()] -> submitAll())
        {
            show_msg_box("提交失败");
        }
        else
        {
            table_changed = false;
            ui -> exit_upgrade -> click();
            ui -> menuBar -> setVisible(true);
        }
    }
}


void MainWindow::on_exit_upgrade_clicked()
{
    if(table_changed)
    {
        show_msg_box("有未提交的修改");
    }
    else
    {
        ui -> writing_table -> setModel(nullptr);
        ui -> delete_choose -> setEnabled(false);
        table_changed = false;
        ui -> stackedWidget -> setCurrentIndex(1);
        ui -> menuBar -> setVisible(true);
    }
}

void MainWindow::on_db_botton_clicked()
{
    ui -> db_botton -> setEnabled(false);
    if(ui -> db_botton -> text() == "开启数据库")
    {
        ui -> db_status -> setText("开启中");
        QtConcurrent::run(control_db, "gs_om -t start", ui -> db_status, ui -> db_botton, ui -> NodeList, ui -> NodeListDetail);
    }
    else if(ui -> db_botton -> text() == "关闭数据库")
    {
        ui -> db_status -> setText("关闭中");
        QtConcurrent::run(control_db, "gs_om -t stop", ui -> db_status, ui -> db_botton, ui -> NodeList, ui -> NodeListDetail);
    }
    else if(ui -> db_botton -> text() == "重试")
    {
        ui -> db_status -> setText("正在获取");
        QtConcurrent::run(get_db_status, ui -> db_status, ui -> db_botton, ui -> NodeList, ui -> NodeListDetail);
    }
}

void MainWindow::on_start_sql_clicked()
{
    QStringList Commands;

    if(ui -> sql_edit -> toPlainText().contains(';'))
    {
        Commands = ui -> sql_edit -> toPlainText().split(';');
    }
    else
    {
        Commands.append(ui -> sql_edit -> toPlainText());
    }

    ui -> sql_return -> setText("");
    QString result = "";

    for(int i = 0; i < Commands.size(); i++)
    {
        if(Commands[i].isEmpty() == false)
        {
            start_sql_query(Commands[i]);

            if(i != 0)
            {
                result = result + "\n";
            }

            if(db_helper -> isActive())
            {
                result = result + "成功执行";

                QSqlRecord rec = db_helper -> record();
                int columns = rec.count();
                int arrange = 0;

                QString table_return = "";

                for(int i = 0; i < db_helper -> record().count(); i++)
                {
                    table_return = table_return + db_helper -> record().fieldName(i) + " \t";
                    if(i == db_helper -> record().count() - 1)
                    {
                        table_return = table_return + "\n";
                    }
                }

                while (db_helper -> next())
                {
                    arrange++;
                    for(int i = 0; i < columns; i++)
                    {
                        if(i != 0)
                        {
                            table_return = table_return + " \t";
                        }
                        table_return = table_return + db_helper -> value(i).toString();
                    }
                    table_return = table_return + "\n";
                }

                result = result + " 结果行数为" + QString::number(arrange) + "\n" + table_return + "\n";
            }
            else
            {
                result = "SQL:" + Commands[i] + "有误\n";
                result = result + db_helper -> lastError().text();
            }

            db_helper -> clear();
        }
    }


    ui -> sql_return -> setText(result);
}

void MainWindow::on_actioncsv_triggered()
{
    QString name = ui -> table_index -> tabText(ui -> table_index -> currentIndex());

    if(name.isEmpty())
    {
        name = ui -> table_index -> tabText(ui -> table_index -> currentIndex());
    }

    write_file(name, view_model[table_model[name] -> model()], table_model[name], csv);
}


void MainWindow::on_action_og_db_export_triggered()
{
    QString name = ui -> table_index -> tabText(ui -> table_index -> currentIndex());

    if(name.isEmpty())
    {
        name = ui -> table_index -> tabText(ui -> table_index -> currentIndex());
    }

    write_file(name, view_model[table_model[name] -> model()], table_model[name], og_db);
}

void MainWindow::on_actionxls_triggered()
{
    QString name = ui -> table_index -> tabText(ui -> table_index -> currentIndex());

    if(name.isEmpty())
    {
        name = ui -> table_index -> tabText(ui -> table_index -> currentIndex());
    }

    write_file(name, view_model[table_model[name] -> model()], table_model[name], xls);
}

void MainWindow::on_actionxlsx_triggered()
{
    QString name = ui -> table_index -> tabText(ui -> table_index -> currentIndex());

    if(name.isEmpty())
    {
        name = ui -> table_index -> tabText(ui -> table_index -> currentIndex());
    }

    write_file(name, view_model[table_model[name] -> model()], table_model[name], xlsx);
}

void MainWindow::on_action_og_db_import_triggered()
{
    read_file(og_db, ui -> table_list);
}

void MainWindow::on_action_help_triggered()
{
    show_msg_box("双击左边的表以操作表");
}

void MainWindow::on_action_setting_triggered()
{
    if(setting -> open_dir_after_create_file)
    {
        ui -> open_dir -> setCheckState(Qt::Checked);
    }
    else
    {
        ui -> open_dir -> setCheckState(Qt::Unchecked);
    }

    if(setting -> backup_table_before_change_table)
    {
        ui -> backup_table -> setCheckState(Qt::Checked);
    }
    else
    {
        ui -> backup_table -> setCheckState(Qt::Unchecked);
    }

    ui -> backup_dir -> setText(setting -> backup_dir);
    ui -> stackedWidget -> setCurrentIndex(5);
    ui -> menuBar -> setVisible(false);
}

void MainWindow::on_setting_page_back_clicked()
{
    ui -> stackedWidget -> setCurrentIndex(1);
    ui -> menuBar -> setVisible(true);
}


void MainWindow::on_open_dir_stateChanged(int arg1)
{
    if(arg1 == Qt::Checked)
    {
        setting -> open_dir_after_create_file = true;
    }
    else if(arg1 == Qt::Unchecked)
    {
        setting -> open_dir_after_create_file = false;
    }

    setting -> save_set();
}

void MainWindow::on_actionbug_report_triggered()
{
    QString url = "https://gitee.com/ma4567/database_controller_for_gbase8c/issues";
    QDesktopServices::openUrl(QUrl(url.toLatin1()));
}

void MainWindow::on_fresh_table_clicked()
{
    view_model[table_model[ui -> table_index -> tabText(ui -> table_index -> currentIndex())] -> model()] -> select();
}

void MainWindow::on_backup_table_stateChanged(int arg1)
{
    if(arg1 == Qt::Checked)
    {
        setting -> backup_table_before_change_table = true;
    }
    else if(arg1 == Qt::Unchecked)
    {
        setting -> backup_table_before_change_table = false;
    }

    setting -> save_set();
}

void MainWindow::on_backup_dir_editingFinished()
{
    QFileInfo info(ui -> backup_dir -> text());
    if(info.isDir())
    {
        setting -> backup_dir = ui -> backup_dir -> text();
        setting -> save_set();
    }
    else
    {
        ui -> backup_dir -> setText(setting -> backup_dir);
        show_msg_box("无效的路径");
    }
}

void MainWindow::on_choose_backup_dir_clicked()
{
    QString dir_location = QFileDialog::getExistingDirectory(NULL,"选择备份文件保存路径",".");

    if(dir_location.isEmpty() == false)
    {
        ui -> backup_dir -> setText(dir_location);
        setting -> backup_dir = ui -> backup_dir -> text();
        setting -> save_set();
    }
}

void MainWindow::on_pushButton_clicked()
{
    QDesktopServices::openUrl(QUrl::fromLocalFile(setting -> backup_dir));
}

bool ChangeSqlFile = false;
bool NewSqlFile = false;

void MainWindow::on_action_build_SQL_triggered()
{
    NewSqlFile = true;
    ChangeSqlFile = true;

    ui -> stackedWidget -> setCurrentIndex(4);
    ui -> menuBar -> setVisible(false);

    ui -> SQLFIlePath -> setText("新SQL文件");
    ui -> SaveNotice -> setText("*");

    ui -> sql_edit -> clear();
}

void MainWindow::on_action_read_SQL_triggered()
{
    QString SqlFilePath = QFileDialog::getOpenFileName(this, "选择SQL文件", "", "SQL (*.sql)");

    if(SqlFilePath.isEmpty() == false)
    {
        ui -> sql_edit -> clear();

        QFile SqlFile(SqlFilePath);
        if(SqlFile.open(QIODevice::ReadOnly))
        {
            ui -> sql_edit -> setText(SqlFile.readAll());

            ui -> SQLFIlePath -> setText(SqlFilePath);

            ui -> stackedWidget -> setCurrentIndex(4);
            ui -> menuBar -> setVisible(false);

            ui -> SaveNotice -> setText(" ");
        }
        SqlFile.close();

        NewSqlFile = false;
        ChangeSqlFile = false;
    }
}

void MainWindow::on_sql_edit_textChanged()
{
    ChangeSqlFile = true;
    ui -> SaveNotice -> setText("*");
}

void MainWindow::keyPressEvent(QKeyEvent* event)
{
    if(ui -> stackedWidget -> currentIndex() == 4)
    {
        if(event -> modifiers() == Qt::ControlModifier)
        { // 如果按下了CTRL键
            if(event -> key() == Qt::Key_S)
            {
                QString SaveFilePath = WriteSqlFile(ui -> sql_edit, NewSqlFile, ui -> SQLFIlePath -> text());

                if(SaveFilePath.isEmpty() == false)
                {
                    if(NewSqlFile)
                    {
                        ui -> SQLFIlePath -> setText(SaveFilePath);
                    }

                    ui -> SaveNotice -> setText(" ");
                    ChangeSqlFile = false;
                    NewSqlFile = false;
                }
            }
        }
    }
}

void MainWindow::on_sql_page_back_clicked()
{
    bool CouldBack = true;
    if(ChangeSqlFile)
    {
        if(NewSqlFile)
        {
            if(ui -> sql_edit -> toPlainText().isEmpty() == false)
            {
                show_msg_box("有编辑中的SQL文件未保存");
                CouldBack = false;
            }
        }
        else
        {
            show_msg_box("有编辑中的SQL文件未保存");
            CouldBack = false;
        }
    }

    if(CouldBack)
    {
        ui -> stackedWidget -> setCurrentIndex(1);
        get_all_table();
        ui -> menuBar -> setVisible(true);

        ui -> sql_edit -> clear();
        NewSqlFile = false;
        ChangeSqlFile = false;
    }
}

void MainWindow::on_SaveSQLButton_clicked()
{
    QString SaveFilePath = WriteSqlFile(ui -> sql_edit, NewSqlFile, ui -> SQLFIlePath -> text());

    if(SaveFilePath.isEmpty() == false)
    {
        if(NewSqlFile)
        {
            ui -> SQLFIlePath -> setText(SaveFilePath);
        }

        ui -> SaveNotice -> setText(" ");
        ChangeSqlFile = false;
        NewSqlFile = false;
    }
}

void MainWindow::on_action_node_manager_triggered()
{
    ui -> menuBar -> setVisible(false);
    ui -> stackedWidget -> setCurrentIndex(6);

    FreshNodeList(ui -> NodeList, ui -> NodeListDetail);
}

void MainWindow::on_NodeListDetail_cellClicked(int row, int column)
{
    QString NodeStatus = ui -> NodeListDetail -> item(row, 3) -> text();

    if(NodeStatus == "已启动")
    {
        ui -> OpenNode -> setEnabled(false);
        ui -> RestartNode -> setEnabled(true);
        ui -> StopNode -> setEnabled(true);
    }
    else
    {
        ui -> OpenNode -> setEnabled(true);
        ui -> RestartNode -> setEnabled(false);
        ui -> StopNode -> setEnabled(false);
    }
}

void MainWindow::on_LeaveNodeManager_clicked()
{
    ui -> menuBar -> setVisible(true);
    ui -> stackedWidget -> setCurrentIndex(1);
}

void MainWindow::on_OpenNode_clicked()
{
    QString CurrentHost = ui -> NodeListDetail -> item(ui -> NodeListDetail -> currentRow(), 0) -> text();

    if(ui -> NodeListDetail -> item(ui -> NodeListDetail -> currentRow(), 4) -> text() == "主实例")
    {
        show_msg_box("主实例不支持该操作");
    }
    else
    {
        LinuxController::RunCommand("gs_om -t start -h " + CurrentHost);
        LinuxController::FreshNodeList(ui -> NodeList, ui -> NodeListDetail);
    }

    ui -> OpenNode -> setEnabled(false);
    ui -> RestartNode -> setEnabled(false);
    ui -> StopNode -> setEnabled(false);
}

void MainWindow::on_RestartNode_clicked()
{
    QString CurrentHost = ui -> NodeListDetail -> item(ui -> NodeListDetail -> currentRow(), 0) -> text();

    if(ui -> NodeListDetail -> item(ui -> NodeListDetail -> currentRow(), 4) -> text() == "主实例")
    {
        show_msg_box("主实例不支持该操作");
    }
    else
    {
        LinuxController::RunCommand("gs_om -t restart -h " + CurrentHost);
        LinuxController::FreshNodeList(ui -> NodeList, ui -> NodeListDetail);
    }

    ui -> OpenNode -> setEnabled(false);
    ui -> RestartNode -> setEnabled(false);
    ui -> StopNode -> setEnabled(false);
}

void MainWindow::on_StopNode_clicked()
{
    QString CurrentHost = ui -> NodeListDetail -> item(ui -> NodeListDetail -> currentRow(), 0) -> text();

    if(ui -> NodeListDetail -> item(ui -> NodeListDetail -> currentRow(), 4) -> text() == "主实例")
    {
        show_msg_box("主实例不支持该操作");
    }
    else
    {
        LinuxController::RunCommand("gs_om -t stop -h " + CurrentHost);
        LinuxController::FreshNodeList(ui -> NodeList, ui -> NodeListDetail);
    }

    ui -> OpenNode -> setEnabled(false);
    ui -> RestartNode -> setEnabled(false);
    ui -> StopNode -> setEnabled(false);
}

void MainWindow::on_action_user_manager_triggered()
{
    ui -> menuBar -> setVisible(false);
    ui -> stackedWidget -> setCurrentIndex(7);

    ui -> AddNewUser -> setEnabled(false);
    ui -> DeleteUser -> setEnabled(false);

    SQLHelper::FillTableModel(ui -> UserTable, "pg_user", this);
}

void MainWindow::on_UserTable_cellClicked(int row, int column)
{
    ui -> UserNameInput -> setText(ui -> UserTable -> item(row, 0) -> text());
    ui -> UserPwdInput -> setText(ui -> UserTable -> item(row, 6) -> text());

    ui -> AddNewUser -> setEnabled(false);
    ui -> DeleteUser -> setEnabled(true);
}

void MainWindow::on_UserNameInput_textChanged(const QString &arg1)
{
    bool NewName = true;

    for(int i = 0; i < ui -> UserTable -> rowCount(); i++)
    {
        if(arg1 == ui -> UserTable -> item(i, 0) -> text())
        {
            NewName = false;
        }
    }

    if(NewName)
    {
        ui -> AddNewUser -> setEnabled(true);
        ui -> DeleteUser -> setEnabled(false);
    }
    else
    {
        ui -> AddNewUser -> setEnabled(false);
        ui -> DeleteUser -> setEnabled(true);
    }
}

void MainWindow::on_UserPwdInput_textChanged(const QString &arg1)
{
    bool NewName = true;

    for(int i = 0; i < ui -> UserTable -> rowCount(); i++)
    {
        if(arg1 == ui -> UserTable -> item(i, 0) -> text())
        {
            NewName = false;
        }
    }

    if(NewName)
    {
        ui -> AddNewUser -> setEnabled(true);
        ui -> DeleteUser -> setEnabled(false);
    }
    else
    {
        ui -> AddNewUser -> setEnabled(false);
        ui -> DeleteUser -> setEnabled(true);
    }
}

void MainWindow::on_AddNewUser_clicked()
{
    bool NewName = true;

    for(int i = 0; i < ui -> UserTable -> rowCount(); i++)
    {
        if(ui -> UserNameInput -> text() == ui -> UserTable -> item(i, 0) -> text())
        {
            NewName = false;
        }
    }

    if(NewName)
    {
        QString command = "CREATE USER " + ui -> UserNameInput -> text() + " CREATEDB PASSWORD \'" + ui -> UserPwdInput -> text() + "\'";
        start_sql_query(command);
        SQLHelper::FillTableModel(ui -> UserTable, "pg_user", this);

        ui -> AddNewUser -> setEnabled(false);
        ui -> DeleteUser -> setEnabled(false);
    }
    else
    {
        show_msg_box("该用户已存在");
    }
}

void MainWindow::on_DeleteUser_clicked()
{
    QString command = "DROP USER " + ui -> UserNameInput -> text() + " CASCADE ";
    start_sql_query(command);
    SQLHelper::FillTableModel(ui -> UserTable, "pg_user", this);

    ui -> AddNewUser -> setEnabled(false);
    ui -> DeleteUser -> setEnabled(false);
}

void MainWindow::on_LeaveUserManager_clicked()
{
    ui -> menuBar -> setVisible(true);
    ui -> stackedWidget -> setCurrentIndex(1);

    ui -> AddNewUser -> setEnabled(false);
    ui -> DeleteUser -> setEnabled(false);
}

